﻿from socket import * 
import thread 
version="0.0.3"
####IZomert gama server
from server_addition import Logger,QueryMaster
from map import *



class Server:
    #config
    HOST = ''
    PORT=11337
    BUFSIZ = 2048
    ADDR = (HOST, PORT)
    
           
    def __init__(self,size=100,levels=2):
        #tech
        self.QueryMaster=QueryMaster()
        self.Logger=Logger("log.txt")
        
        self.Map=Map(size,levels)
        self.Map.draw_map()
        #############
        self.serversock = socket(AF_INET, SOCK_STREAM)
        self.serversock.bind(self.ADDR)
        self.serversock.listen(5)
        #lets go
        self.main_loop()
        
    def connection_resive(self,clientsock,addr,id):
        while 1:
            data = clientsock.recv(self.BUFSIZ)
            
            if not data:    #disconaction
                break 
            else:           #allright
                thread.start_new_thread(self.connection_send,(data,id))
               
        clientsock.close()
        self.QueryMaster.disconected(id)       
        print "user disconected %s : %s" %(str(addr[0]),str(addr[1]))
            
    def connection_send(self,data,id):       
        self.Logger.log(data, "<<")
        request=self.QueryMaster.new_qeuery(id, data)#reqest=**(id,id_query,resived,cmd)
        #получаем ответ серевера и отслываем его
        msg=self.wisher(**request)
        if not msg==False:                          #если пришел фалс значит чтото не так все остолное хорошо удаляем квери                    
            if not msg==True:
                del self.QueryMaster.querys[id][self.QueryMaster.sender(request["id"],request["id_query"], msg)]
            else:
                del self.QueryMaster.querys[id][request["id_query"]]
                self.Logger.log(data, ">>")
        else:
            print "bad query by"+str(addr) 
            
               
    def main_loop(self):
        while 1:
            print "Hi im izometr gama server ver  %s port : %s" %(version,self.PORT)
            print "-"*40
            clientsock, addr = self.serversock.accept()
            print "someone connected from: %s"%(addr[0]) 
            thread.start_new_thread(self.connection_resive,(self.QueryMaster.new_player(clientsock, addr)))
            
            
        
    def wisher(self,id,id_query,resived,cmd):
        #cmd= splited  "&" 
        if resived=="3":
            print 'user %s >> %s' %(id, cmd[1])
            msg=cmd[1]
            self.QueryMaster.send_to_all(cmd[1],id,id_query)
            return True
        
        ##########/4###########
        if resived=="4":
            #MAP sender
            
            msg="%s.%s/4&%s;%s&%s;%s&%s&"%(id,id_query,self.Map.granica_niz,self.Map.granica_verh-1,self.Map.granica_niz,self.Map.granica_verh-1,self.Map.levels)
            rev=range(self.Map.granica_niz,self.Map.granica_verh)
            rev.reverse()
            voda=0
            for level in self.Map.map:
                map=self.Map.map[level]
                
                for x in range(self.Map.granica_niz,self.Map.granica_verh):
                    for y in rev:
                        if map[x,y]==0:
                            voda+=1
                        else:
                            if voda>0:
                               msg+="w"+str(voda)+";"
                               voda=0
                            #zdes nujna pravka typov 
                            msg+="2.1;"     
            if(voda>0):
                msg+="w"+str(voda)+";"
            msg=msg[:-1]
            
            
            #SENDING and sending for  300 symbols
            part=0
            msg_len=300
            partend=1
            self.QueryMaster.queue[id]=False
            while 1:
                if len(msg)<partend*msg_len:
                     self.QueryMaster.users[id][0].send(msg[part*msg_len:len(msg)]+chr(0))
                     print "sending map"
                     break
                else:
                     self.QueryMaster.users[id][0].send(msg[part*msg_len:partend*300])
                     partend+=1
                     part+=1  
            self.QueryMaster.queue[id]=True
            
            return True
        
       
            
        
            
        
       
       
        
        try:
            return msg #если есть что послыать послыем
        except:
            return False#если нет то возвращаем эрор
        
        
map_size=60        #kletok

Server = Server(map_size)

        